package org.example.disruptor;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.function.Consumer;

/**
 * @author weigang
 * @create 2022-07-11 15:15
 */
@Component
@Slf4j
public class StatEnableEventHandler {
    @Autowired
    private DisruptorStat disruptorStat;

    private String CONTENT_FORMAT = "Event:%s,  Exception:%s";

    // @PostConstruct 被注解的方法，等对象依赖全部加载完后再执行
    @PostConstruct
    public void postConstruct() {
        log.info("StatEnableEventHandler postConstruct, mailTo:{}");
    }

    // 函数式接口
    public <T extends Serializable> void doHandle(Consumer<T> func, T event) {
        try {
            // 消费事件
            func.accept(event);
            log.info("Consumer Event Success ,content ：{}, Thread-id :{}", JSON.toJSON(event),Thread.currentThread().getId());
        } catch (Exception e) {
            // 消费失败发送告警邮件
            log.warn("handle Event failed, event:{}, err:{}", event, Throwables.getStackTraceAsString(e));
        } finally {
            // 当前正在执行或者待执行的事件数量 -1
            disruptorStat.currentEventCounter.decrementAndGet();
        }
    }
}
